package core.net;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.alibaba.fastjson.JSON;

import log.mm_logger;
import utils.mm_thread;

/**
 * cdn
 * @author dongyazhuo
 */
public class mm_cdn implements Runnable {

	private String TAG = mm_cdn.class.getSimpleName() + " : ";

	private ArrayList<cdn> list = new ArrayList<cdn>();

	private mm_http_client _mm_http_client;

	private boolean ok = false;

	private Map<String, Object> url = null;

	private static Random random = new Random();

	public mm_cdn(mm_http_client _mm_http_client, Map<String, Object> url) {
		super();
		this._mm_http_client = _mm_http_client;
		this.url = url;
	}

	/**
	 * 获取cdn地址
	 * @return
	 */
	public String get_cdn() {
		if (!ok) {
			mm_logger.i(TAG + "current request cdn address ip: " + "cdn test no finished ...");
			return null;
		} else {
			int r = random.nextInt((int) (list.size() / 100) + 1);
			String ip = list.get(r).ip;
			mm_logger.i(TAG + "current request cdn address ip: " + ip);
			return ip;
		}
	}

	@Override
	public void run() {
		mm_logger.i(TAG + " do begin cdn test ... ");
		test();
	}

	private List<String> read_file() {
		List<String> result = new ArrayList<String>();
		try {
			String encoding = "UTF-8";
			// 读取cdn列表
			InputStream inputStream = mm_cdn.class.getResourceAsStream("/cdn_list");
			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, encoding));
			String has = null;
			while (true) {
				if ((has = br.readLine()) != null) {
					if (!has.trim().equals("")) {
						result.add(has.trim());
					}
					result.add(has);
				} else {
					break;
				}
			}
			br.close();
		} catch (Exception e) {
			mm_logger.e(TAG + e.getMessage());
		}
		return result;
	}

	private void test() {
		List<String> list = read_file();

		for (String ip : list) {
			this.list.add(new cdn(ip));
		}

		while (true) {
			int i = 0;
			for (cdn cdn : this.list) {
				url.put("test_cdn", cdn.ip);
				long start_time = System.currentTimeMillis();
				String result = _mm_http_client.send(url, new HashMap<>()).toString();
				long end_time = System.currentTimeMillis();
				if (null != result && !result.contains("message")) {
					cdn.use_time = end_time - start_time;
				}
				i++;
				mm_thread.sleep(50L);
				NumberFormat numberFormat = NumberFormat.getInstance();
				// 设置精确到小数点后2位
				numberFormat.setMaximumFractionDigits(2);
				String _zcore = numberFormat.format((float) i / (float) list.size() * 100);
				if (_zcore.endsWith("0")) {
					mm_logger.d(TAG + "cdn check progress " + String.format("%3s", _zcore) + "% ... ...");
				}
			}
			// 排序
			Collections.sort(this.list, new sort_by_time());
			this.ok = true;
		}

	}

	class cdn {
		public String ip;
		public Long use_time = 1000L;

		public cdn(String ip) {
			super();
			this.ip = ip;
		}

		public cdn(String ip, long time) {
			super();
			this.ip = ip;
			this.use_time = time;
		}

		@Override
		public String toString() {
			return JSON.toJSONString(this);
		}
	}

	/**
	 * 排序
	 * @author dongyazhuo
	 */
	class sort_by_time implements Comparator<cdn> {
		public int compare(cdn cdn1, cdn cdn2) {
			if (cdn1.use_time > cdn2.use_time)
				return 1;
			return -1;
		}
	}

}
